<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-button type="primary" @click="checkOrder">查看单据</el-button>
        <el-button
          :disabled="!buttonsPermissions.DaoChu"
          :class="!buttonsPermissions.DaoChu ? 'disabled_button' : ''"
          @click="exportExcel"
          >导出</el-button
        >
        <el-button
          :disabled="!buttonsPermissions.DaYin"
          :class="!buttonsPermissions.DaYin ? 'disabled_button' : ''"
          @click="handleShortcutKeyPrint"
          >打印(P)</el-button
        >
        <el-checkbox v-model="queryData.isShowHcdj">隐藏红冲单据</el-checkbox>
        <el-checkbox v-model="queryData.isShowZfdj">隐藏作废单据</el-checkbox>
      </div>
      <div class="btn_right">
        <el-input v-model="queryData.fuzzyQueryParam" placeholder="请输入单据编号\往来单位名称\关键字搜索"></el-input>
        <el-button type="primary" @click="onQuery">搜索</el-button>
        <el-button @click="onRefresh">刷新</el-button>
        <i @click="onShowColumn()" class="set_up el-icon-s-tools"></i>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_table" ref="divTable">
        <div class="div_screen" ref="divScreen">
          <div class="screen_left">
            <div class="line_dialog">
              <p>客户</p>
              <el-tooltip
                :disabled="queryData.xghCompany.length <= 6"
                effect="dark"
                :content="queryData.xghCompany"
                :enterable="false"
                placement="bottom-start"
              >
                <p class="dialog_input">
                  <el-select
                    v-model="queryData.xghCompanyId"
                    @change="onSelectCompany"
                    filterable
                    @visible-change="(value) => handleFilterMethod('', 'companyName')"
                    :filter-method="(value) => handleFilterMethod(value, 'companyName')"
                    ref="kehu"
                  >
                    <el-option
                      v-for="item in gysOptions"
                      :key="item.id"
                      :label="item.companyName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <i @click="onShowSupplier" class="el-icon-more"></i>
                </p>
              </el-tooltip>
            </div>
            <div>
              <p>仓库</p>
              <el-select
                v-model="queryData.xghOutStorehouseId"
                filterable
                @visible-change="(value) => handleFilterMethod('', 'storehouseName')"
                :filter-method="(value) => handleFilterMethod(value, 'storehouseName')"
                @change="onClickStorehouse"
                ref="cangku"
              >
                <el-option
                  v-for="item in storehouseOptions"
                  :key="item.id"
                  :label="item.storehouseName"
                  :value="item.id"
                ></el-option>
                <!-- <el-option key label value>
                  <div class="custom_add" @click.stop="onStorehouseAdd">
                    <i class="el-icon-plus"></i>
                    <span>新增</span>
                  </div>
                </el-option>-->
              </el-select>
            </div>
            <div>
              <p>经手人</p>
              <el-select
                filterable
                v-model="queryData.sysUserId"
                ref="yewuyuan"
                @visible-change="(value) => handleFilterMethod('', 'realname')"
                :filter-method="(value) => handleFilterMethod(value, 'realname')"
              >
                <el-option
                  v-for="item in ywyOptions"
                  :key="item.id"
                  :label="item.realname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
            <div>
              <p>单据编号</p>
              <el-input
                v-if="queryData.orderNumber.length <= 6"
                type="text"
                placeholder="请输入"
                v-model="queryData.orderNumber"
              />
              <el-tooltip
                v-else
                effect="dark"
                :content="queryData.orderNumber"
                :enterable="false"
                placement="bottom-start"
              >
                <el-input type="text" placeholder="请输入" v-model="queryData.orderNumber" />
              </el-tooltip>
            </div>
            <div class="line_dialog">
              <p>商品名称</p>
              <el-tooltip
                :disabled="queryData.goodsName.length <= 6"
                effect="dark"
                :content="queryData.goodsName"
                :enterable="false"
                placement="bottom-start"
              >
                <p class="dialog_input">
                  <el-select
                    v-model="queryData.goodsId"
                    filterable
                    @visible-change="(value) => handleFilterMethod('', 'goodsName')"
                    :filter-method="(value) => handleFilterMethod(value, 'goodsName')"
                  >
                    <el-option
                      v-for="item in spmcOptions"
                      :key="item.id"
                      :label="item.goodsName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <i @click="onShowCommodity" class="el-icon-more"></i>
                </p>
              </el-tooltip>
            </div>
            <div>
              <p>单据状态</p>
              <el-select v-model="queryData.orderStatusStr" filterable @change="orderStatusChange">
                <el-option
                  v-for="item in djztOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <!-- 统计范围 -->
            <div class="custom_item" style="width: auto">
              <p>统计范围</p>
              <!-- <div class="item_title" style="margin-right: 15px;">统计范围</div> -->
              <div class="custom_select_head">
                <el-checkbox-group v-model="queryData.orderTypeStr" :min="1" style="display: flex">
                  <el-checkbox v-for="item in cxfwOptions" :label="item.value" :key="item.value">{{
                    item.label
                  }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div class="screen_right">
            <el-select filterable @change="changeDate" v-model="monthValue">
              <el-option
                v-for="item in monthOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <!-- <div class="date_picker_style" v-if="isShowDate">
              <p>{{ queryData.dateRange.startDate }}~{{ queryData.dateRange.endData }}</p>
              <el-date-picker
                v-model="nowDate"
                type="daterange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="onClickPicker"
              >
              </el-date-picker>
              <i class="el-icon-date"></i>
            </div>-->
            <el-date-picker
              v-if="isShowDate"
              v-model="nowDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="onClickPicker"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <el-button type="primary" @click="onQuery">查询</el-button>
          </div>
        </div>
        <div class="table_content" :style="{ height: tableHeight + 'px' }">
          <el-table
            ref="tableList"
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            :header-cell-style="{
              color: '#666666',
              textAlign: 'center',
              height: '30px',
              borderColor: '#dddddd',
            }"
            border
            :cell-style="{ textAlign: 'center' }"
            :data="tableData"
            height="100%"
            style="width: 100%"
            @row-click="clickRow"
            @row-dblclick="handleRowDbclick"
          >
            <el-table-column :resizable="false" label="序号" type="index" width="50"></el-table-column>
            <template v-for="(item, index) in columnData">
              <el-table-column
                :show-overflow-tooltip="true"
                :key="index"
                border
                :label="item.zidingyiName ? item.zidingyiName : item.morenName"
                v-if="item.zidingyiState"
                :prop="item.props"
                min-width="130px"
                :sortable="item.sortable"
                :resizable="item.props== 'goodsId_dictText'?true:false"
                :width="item.props == 'orderNumber' ? '170px' :''"
              >
                <template slot-scope="scope" >
                  <span v-if="monarr.includes(item.props)">{{ $formatMoney(scope.row[item.props]) }}</span>
                  <span v-else-if="priarr.includes(item.props)">{{ $formatPrice(scope.row[item.props]) }}</span>
                  <span v-else-if="item.props=='goodsId_dictText'" style="width: 100%; white-space: normal;
  word-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical; text-align: left;">{{ scope.row[item.props] }}</span>
                  <span v-else-if="numarr.includes(item.props)">{{ $formatNumber(scope.row[item.props]) }}</span>
                  <span v-else>{{ scope.row[item.props] }}</span>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="pagesize"
              layout="jumper, prev, pager,next, sizes"
              :total="total"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 选择客户弹框 -->
    <DialogSupplier ref="supplierRef" @onSelectSupplier="onSelectSupplier"></DialogSupplier>
    <!-- 新增客户弹框 -->
    <DialogSupplierAdd ref="supplierAddRef" @onAddSubmit="onAddSupplier"></DialogSupplierAdd>
    <!-- 新增仓库弹框 -->
    <DialogWarehouseAdd ref="warehouseAddRef" :newData="newWhData" @onAddSubmit="onAddWh" @handleClose="onCloseAddWh">
    </DialogWarehouseAdd>
    <!-- 选择商品弹框 -->
    <DialogCommoditySingle ref="commodityRef" @onSelectCommodity="onSelectCommodity"></DialogCommoditySingle>
    <!-- 列配置弹框 -->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="columnData"
      :defaultColumnDataArr="defaultColumnData"
      orderType="销售毛利明细表"
      @onSaveColumn="onSaveColumn"
    >
    </CConfiguration>
    <!-- 新增树形结构数据弹框 -->
    <NewCategory
      v-if="showNewTree"
      :newTreeData="newTreeData"
      @onSaveTreeChanges="onSaveTreeChanges"
      @onCancelTree="onCancelTree"
    ></NewCategory>
    <!-- 打印 -->
    <dialog-print ref="print"></dialog-print>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CConfiguration from '@/components/c_column/columnConfiguration1'
import NewCategory from '@/components/c_category/NewCategory'
import DialogSupplier from '../../components/dialogSupplier'
import DialogSupplierAdd from '../../components/dialogSupplierAdd'
// 仓库新增
import DialogWarehouseAdd from '../../components/dialogWarehouseAdd'
import DialogCommoditySingle from '@/views/components/dialogCommoditySingle'
/**打印 */
import dialogPrint from '@/views/components/dialogPrintStatic'
import { getAction, postAction, downPostFile } from '@/api/manage'
import { dateStrFromDate } from '@/utils/DateFormatter'
import { toBillDetail } from '@/utils/billUtil'
import { handlePermissions, handleOtherPerms } from '@/utils/index'
import { ACCESS_TOKEN, TENANT_ID, ACCOUNT_BOOK } from '@/store/mutation-types'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Vue from 'vue'
import { delcommafy } from '../../../utils'
export default {
  name: 'salesGrossProfit',
  mixins: [JeecgListMixin],
  components: {
    CConfiguration,
    NewCategory,
    DialogSupplier,
    DialogSupplierAdd,
    DialogWarehouseAdd,
    DialogCommoditySingle,
    dialogPrint,
  },
  computed: {
    ...mapGetters(['name']),
    buttonsPermissions() {
      return handlePermissions(this.pageName)
    },
    printPermissions() {
      return handleOtherPerms('单据可多次打印')
    },
  },
  created() {
    // 默认获取当月时间
    this.getTimeRange(this.$setTimeRange(5))
    this.getData()
  },
  watch: {
    'queryData.isShowHcdj': {
      deep: true,
      handler() {
        // if (this.queryData.isShowHcdj) {
        //   this.queryData.orderStatusStr = '5'
        // } else {
        //   this.queryData.orderStatusStr = '20'
        // }
        let str = JSON.stringify(this.queryData)
        let arr = JSON.parse(str)
        this.currentPage = 1
        this.requestQuery(arr)
      },
    },
    'queryData.isShowZfdj': {
      deep: true,
      handler() {
        let str = JSON.stringify(this.queryData)
        let arr = JSON.parse(str)
        this.currentPage = 1
        this.requestQuery(arr)
      },
    },
    'queryData.xghCompanyId': {
      deep: true,
      handler() {
        this.gysOptions.forEach((item) => {
          if (item.id == this.queryData.xghCompanyId) {
            this.queryData.xghCompany = item.companyName
          }
        })
      },
    },
    'queryData.goodsId': {
      deep: true,
      handler() {
        console.log(this.queryData.goodsId)
        this.totalGoods.forEach((item) => {
          if (item.id == this.queryData.goodsId) {
            this.queryData.goodsName = item.goodsName
          }
        })
      },
    },
  },
  data() {
    return {
      // 客户
      gysOptions: [],
      // 仓库
      storehouseOptions: [],
      // 新增仓库数据
      newWhData: {},
      // 经手人
      ywyOptions: [],
      // 商品名称
      spmcOptions: [],
      // 查询范围
      cxfwOptions: [
        {
          value: '6',
          label: '销售出库单',
        },
        {
          value: '7',
          label: '销售退货单',
        },
        {
          value: '8',
          label: '销售换货单',
        },
      ],
      // 单据状态
      djztOptions: [
        {
          value: '5,0,20,10',
          label: '全部',
        },
        {
          value: '5',
          label: '已审核',
        },
        {
          value: '0',
          label: '待审核',
        },
        {
          value: '10',
          label: '已作废',
        },
        {
          value: '20',
          label: '已红冲',
        },
      ],
      // 查询条件数据
      queryData: {
        // 直接触发
        isShowHcdj: false,
        isShowZfdj: false,
        //搜索框值
        fuzzyQueryParam: '',
        // 筛选
        xghCompanyId: '', // 客户单位
        xghCompany: '', // 客户单位
        sysUserId: '', // 经手人
        xghOutStorehouseId: '', // 仓库
        orderNumber: '',
        goodsId: '', // 商品id
        goodsName: '', // 商品名称
        orderTypeStr: ['6', '7', '8'],
        orderStatusStr: '5,0,20,10', // 单据状态
        // 日期选择范围
        dateRange: {
          startDate: '',
          endData: '',
        },
      },
      // 月份选择
      monthValue: '本月',
      monthOptions: [
        {
          value: '今日',
          label: '今日',
        },
        {
          value: '本周',
          label: '本周',
        },
        {
          value: '本月',
          label: '本月',
        },
        {
          value: '本年',
          label: '本年',
        },
      ],
      isShowDate: true, // 是否显示选择时间组件
      nowDate: [],
      // 表格数据
      tableData: [],
      defaultColumnData: [],
      // 列配置数据
      columnData: [
        {
          morenName: '单据日期',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'createTime',
          sortable: 'custom',
        },
        {
          morenName: '单据类型',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'orderType_dictText',
        },
        {
          morenName: '客户',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'xghCompanyId_dictText',
        },
        {
          morenName: '经手人',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'sysUserId_dictText',
        },
        {
          morenName: '仓库',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'xghOutStorehouseId_dictText',
        },
        {
          morenName: '商品编号',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'goodsNumber',
        },
        {
          morenName: '商品名称',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'goodsId_dictText',
        },
        {
          morenName: '规格',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'norms',
        },
        {
          morenName: '单位',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'unit',
        },
        {
          morenName: '数量',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'number',
        },
        {
          morenName: '单价',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'salePrice',
        },
        {
          morenName: '折扣率',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'discountRate',
        },
        {
          morenName: '折扣单价',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'discountUnitPrice',
        },
        {
          morenName: '税率',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'taxRate',
        },
        {
          morenName: '税后单价',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'taxUnitPrice',
        },
        {
          morenName: '税额',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'taxPrice',
        },
        {
          morenName: '金额小计',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'allPrice',
        },
        {
          morenName: '成本单价',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'costPrice',
        },
        {
          morenName: '成本金额',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'totalCostPrice',
        },
        {
          morenName: '销售毛利',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'grossProfit',
        },
        {
          morenName: '毛利率',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'grossProfitRate',
        },
        {
          morenName: '赠品',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'isGift_dictText',
        },
        {
          morenName: '单据状态',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'orderStatus_dictText',
        },
        {
          morenName: '制单人',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'createName',
        },
        {
          morenName: '制单日期',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'createOrderDate',
        },
        {
          morenName: '备注',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'remark',
        },
        {
          morenName: '附记',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'postscript',
        },
      ],
      total: 0,
      pagesize: 20, //每页的数据条数
      currentPage: 1, //默认开始页面
      showNewTree: false, //显示树形结构数据新增弹框
      // 传递数据给新增树形结构组件
      newTreeData: {
        parentNode: '',
        nowNode: '',
      },
      orderItem: {},
      updateId: '', // 修改列配置时返回的id
      accountBookId: '', // 当前账套ID
      url: {
        maoList: '/xghSaleStorehouseOrder/xghSaleStorehouseOrder/salesMarginDetailList',
        exportExcel: '/xghSaleStorehouseOrder/xghSaleStorehouseOrder/exportSalesMarginDetailListXls',
      },
      arr: ['taxPrice', 'allPrice', 'totalCostPrice', 'grossProfit', 'number'],
      monarr: ['taxPrice', 'allPrice', 'totalCostPrice', 'grossProfit'],
      priarr: ['salePrice', 'discountUnitPrice', 'taxUnitPrice', 'costPrice'],
      numarr: ['number'],
      pageName: '销售毛利明细',
      printClick: false,
      tableHeight: 1000,
    }
  },
  mounted() {
    this.selectTitle()
    let divScreen = this.$refs.divScreen.offsetHeight
    let divTable = this.$refs.divTable.offsetHeight

    console.log(divScreen)
    console.log(divTable)
    this.tableHeight = divTable - divScreen - 80
  },
  methods: {
    // 打印
    handleShortcutKeyPrint() {
      // 查询
      this.printClick = true
      this.onQuery()
    },
    handlePrint() {
      // 打印
      if (!this.buttonsPermissions.DaYin) {
        this.$elMessage.warning('未拥有打印权限！')
      } else if (!this.tableData || this.tableData.length <= 0) {
        this.$elMessage.warning('没有要打印的记录！')
      } else {
        let printData = {
          riqi: this.queryData.dateRange.startDate + '~' + this.queryData.dateRange.endData,
          kehu: this.$refs.kehu.selected.label,
          cangku: this.$refs.cangku.selected.label,
          yewuyuan: this.$refs.yewuyuan.selected.label,
          printExclusive: this.tableData.map((item) => {
            // 遍历 item 对象的键
            Object.keys(item).map((key) => {
              if (this.numarr.includes(key)) {
                item[key] = this.$formatNumber(item[key])
              } else if (this.monarr.includes(key)) {
                item[key] = this.$formatMoney(item[key])
              } else if (this.priarr.includes(key)) {
                item[key] = this.$formatPrice(item[key])
              }
            })
            return item
          }),
        }
        console.log('打印的数据', printData)
        // 可以多次打印设置
        if (this.printPermissions) {
          this.$refs.print.show(printData, this.columnData, this.pageName)
        } else {
          if (this.$lcStorage.get('printLimitValue')) {
            // 获取打印次数
            this.getPrintNum(this.pageName, () => {
              this.$refs.print.show(printData, this.columnData, this.pageName)
            })
          } else {
            this.$refs.print.show(printData, this.columnData, this.pageName)
          }
        }
      }
    },
    // 查看单据
    checkOrder() {
      if (!this.orderItem || !this.orderItem.orderType) {
        this.$elMessage.warning('请先选择单据！')
        return
      }
      toBillDetail(this, this.orderItem.orderType, this.orderItem.id)
    },
    clickRow(row) {
      this.orderItem = row
    },
    // 双击列表
    handleRowDbclick(row) {
      toBillDetail(this, row.orderType, row.id)
    },
    /**
     *  往来单位相关方法开始
     */
    // 请求客户数据
    getGysStorage() {
      getAction('/xghCompany/xghCompany/listNoPage', {}).then((res) => {
        if (res.code === 200) {
          this.gysOptions = res.result
          this.totalCompanys = res.result
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    // 打开新增往来单位弹出框
    onShowSupplierAdd() {
      this.newData = {
        id: '',
        companyName: '',
        companyUserName: '',
        xghCompanyNatureId: '',
        xghCompanyNature: '',
        companyPhone: '',
        companyPinyinCode: '',
        companyLandline: '',
        xghCompanyTypeId: '', //单位类别
        xghCompanyType: '',
        business: '',
        provinceName: '', //省
        provinceCode: '',
        cityName: '', //市
        cityCode: '',
        countyName: '', //区县
        countyCode: '',
        address: '',
        setPrice: '',
        setDiscountPrice: '',
        companyInvoiceStatus: true,
        depositBank: '',
        bankName: '',
        bakCard: '',
        taxNumber: '',
        invoiceAddress: '',
        bankPhone: '',
        companyRAndPStatus: true,
        beginReceivable: 0,
        beginPayable: 0,
        totalReceivable: 0,
        totalPayable: 0,
        receivableQuota: '',
        payableQuota: '',
        receivableTime: '',
        payableTime: '',
        companyRemark: '',
      }
      this.$refs.supplierAddRef.dialogVisible = true
    },
    // 新增往来单位数据
    onAddSupplier(val) {
      this.getGysStorage()
    },
    // 打开选择往来单位弹出框
    onShowSupplier() {
      this.$refs.supplierRef.dialogVisible = true
    },
    // 当前选择往来单位数据
    onSelectSupplier(val) {
      this.queryData.xghCompanyId = val.id
    },
    // 当前选择往来单位数据
    onSelectCompany(val) {
      this.queryData.xghCompanyId = val
    },
    /**
     *  往来单位相关方法结束
     */

    /**
     *  仓库相关方法开始
     */
    // 仓库信息-下拉框初始化
    getStorehouseOptions() {
      getAction('/xghStorehouse/xghStorehouse/queryListByPole', {}).then((res) => {
        if (res.code === 200) {
          this.storehouseOptions = res.result
          this.totalStores = res.result
        }
      })
    },
    // 选择仓库时触发
    onClickStorehouse(value) {},
    // 打开新增仓库弹出框
    onStorehouseAdd() {
      this.newData = {
        id: '',
        storehouseTypeName: '',
        storehouseCode: '',
        pinyinCode: '',
        indexCode: '',
      }
      this.$refs.warehouseAddRef.dialogVisible = true
    },
    // 新增仓库数据
    async onAddWh(val) {
      val.isMain = val.isMain == true ? 1 : 0
      const res = await postAction('/xghStorehouse/xghStorehouse/add', val)
      if (res.code == 200) {
        // 新增仓库成功之后，刷新仓库下拉框
        this.getStorehouseOptions()
      }
    },
    // 关闭新增仓库时清空新增dialog中的数据
    onCloseAddWh() {
      this.newWhData = this.$options.data().newWhData
    },
    /**
     *  仓库相关方法结束
     */

    // 商品信息
    getGoodsData() {
      getAction('/xghGoods/xghGoods/getGoodsNameList', {}).then((res) => {
        if (res.code === 200) {
          this.spmcOptions = res.result
          this.totalGoods = res.result
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },

    // 打开选择商品弹出框
    onShowCommodity() {
      this.$refs.commodityRef.dialogVisible = true
    },
    // 当前选择商品数据
    onSelectCommodity(val) {
      console.log('选择商品', val)
      this.queryData.goodsId = val.id
      // this.queryData.goodsName = val.goodsName
    },

    // 初始化查询列配置值
    async selectTitle() {
      let obj = await this.$setColumn.selectColumn(this.pageName)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.columnData = obj.columnData
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.pageName, this.columnData, 0, this.updateId)
        this.updateId = id
      }
    },
    // 修改列配置后保存修改后的值
    async onSaveColumn(value) {
      this.columnData = value
      let res = await this.$setColumn.editColumn(this.pageName, this.columnData, this.updateId)
      if (res) {
        this.$elMessage.success('编辑成功!')
      } else {
        this.$elMessage.error('编辑失败!')
      }
    },
    // 导出
    exportExcel() {
      let data = {
        ...this.queryData,
        orderTypeStr: this.queryData.orderTypeStr.join(','),
        beginTime: this.queryData.dateRange.startDate,
        endTime: this.queryData.dateRange.endData,
      }
      downPostFile(this.url.exportExcel, '销售毛利明细表', data)
    },
    // 获取数据
    getData() {
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      this.accountBookId = accountBook && accountBook.id
      this.getGoodsData()
      this.getGysStorage()
      this.getUserList()
      this.getStorehouseOptions()
      this.getTableData()
    },
    // 毛利明细表
    getTableData() {
      let data = {
        ...this.queryData,
        orderTypeStr: this.queryData.orderTypeStr.join(','),
        beginTime: this.queryData.dateRange.startDate,
        endTime: this.queryData.dateRange.endData,
        pageSize: this.pagesize,
        pageNo: this.currentPage,
      }
      postAction(this.url.maoList, data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result.records
          this.total = res.result.total
        } else {
          this.$elMessage.error(res.message)
        }
        if (this.printClick) {
          this.handlePrint()
        }
        this.printClick = false
      })
    },
    // 经手人列表
    getUserList() {
      getAction('/dept/xghAccountBookDept/getAllDeptUsers' + '?abId=' + this.accountBookId).then((res) => {
        console.log('经手人', res)
        if (res.code == 200) {
          this.ywyOptions = res.result
          this.totalPersons = res.result
        }
      })
    },
    // 刷新
    onRefresh() {
      Object.assign(this.$data, this.$options.data())
      this.getData()
      let str = JSON.stringify(this.queryData)
      let arr = JSON.parse(str)
      this.requestQuery(arr)
      this.monthValue = '本月'
      this.getTimeRange(this.$setTimeRange(5))

      let divScreen = this.$refs.divScreen.offsetHeight
      let divTable = this.$refs.divTable.offsetHeight
      this.tableHeight = divTable - divScreen - 80
    },
    // 查询
    onQuery() {
      let str = JSON.stringify(this.queryData)
      let arr = JSON.parse(str)
      arr.dateRange.startDate = arr.dateRange.startDate + ' 00:00:00'
      arr.dateRange.endData = arr.dateRange.endData + ' 23:59:59'
      let obj = {
        ...arr,
      }
      this.currentPage = 1
      this.requestQuery(obj)
    },
    // 请求筛选条件数据
    requestQuery(obj) {
      this.getTableData()
    },
    // 判断当前选择时间段
    changeDate(val) {
      this.isShowDate = true
      switch (val) {
        case '全部':
          this.isShowDate = false
          break
        case '今日':
          this.getTimeRange(this.$setTimeRange(1))
          break
        case '昨天':
          this.getTimeRange(this.$setTimeRange(2))
          break
        case '本周':
          this.getTimeRange(this.$setTimeRange(3))
          break
        case '上周':
          this.getTimeRange(this.$setTimeRange(4))
          break
        case '本月':
          this.getTimeRange(this.$setTimeRange(5))
          break
        case '上月':
          this.getTimeRange(this.$setTimeRange(6))
          break
        case '本年':
          this.getTimeRange(this.$setTimeRange(7))
          break
        case '去年':
          this.getTimeRange(this.$setTimeRange(8))
          break
        default:
          break
      }
    },
    // 获取时间范围并设置
    getTimeRange(data) {
      this.nowDate = [data.now, data.end]
      this.queryData.dateRange.startDate = data.now
      this.queryData.dateRange.endData = data.end
    },
    // 获取当前选中时间
    onClickPicker(val) {
      this.queryData.dateRange.startDate = val[0]
      this.queryData.dateRange.endData = val[1]
    },
    // 类别信息新增/修改后数据获取
    onSaveTreeChanges(value) {
      this.showNewTree = false
      if (this.dialogVisible) {
        this.ruleForm.dwlb = value.lbmc
      } else {
        let tree = this.TreeData
        // this.findTreeNode(tree, value)
        if (this.newTreeData.state == 'add') {
          this.addTreeNode(tree, value)
        } else if (this.newTreeData.state == 'edit') {
          this.editTreeNode(tree, value)
        }
      }
    },
    // 新增树形节点
    addTreeNode(tree, value) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].label == this.newTreeData.nowNode) {
          if (!tree[i].children) {
            this.$set(tree[i], 'children', [])
          }
          tree[i].children.push({
            label: value.lbmc,
            type: String(Number(tree[i].type) + 1),
          })
          return
        } else {
          let treeChildren = this.TreeData[i].children
          for (let i1 = 0; i1 < treeChildren.length; i1++) {
            if (treeChildren[i1].label == this.newTreeData.nowNode) {
              if (!treeChildren[i1].children) {
                this.$set(treeChildren[i1], 'children', [])
              }
              treeChildren[i1].children.push({
                label: value.lbmc,
                type: String(Number(treeChildren[i1].type) + 1),
              })
              return
            } else {
              let treeCChildren = treeChildren[i1].children
              for (let i2 = 0; i2 < treeCChildren.length; i2++) {
                if (treeCChildren[i2].label == this.newTreeData.nowNode) {
                  if (!treeCChildren[i2].children) {
                    this.$set(treeCChildren[i2], 'children', [])
                  }
                  treeCChildren[i2].children.push({
                    label: value.lbmc,
                    type: String(Number(treeCChildren[i2].type) + 1),
                  })
                  return
                }
              }
            }
          }
        }
      }
    },
    // 修改树形节点
    editTreeNode(tree, value) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].label == this.newTreeData.nowNode) {
          tree[i].label = value.lbmc
          return
        } else {
          let treeChildren = this.TreeData[i].children
          for (let i1 = 0; i1 < treeChildren.length; i1++) {
            if (treeChildren[i1].label == this.newTreeData.nowNode) {
              tree[i].label = value.sjlb
              treeChildren[i1].label = value.lbmc
              return
            } else {
              let treeCChildren = treeChildren[i1].children
              for (let i2 = 0; i2 < treeCChildren.length; i2++) {
                if (treeCChildren[i2].label == this.newTreeData.nowNode) {
                  treeChildren[i1].label = value.sjlb
                  treeCChildren[i2].label = value.lbmc
                  return
                }
              }
            }
          }
        }
      }
    },
    // 找到当前需要新增或修改的树形节点（递归循环，暂未使用）
    findTreeNode(tree, value) {
      for (let i = 0; i < tree.length; i++) {
        console.log(tree[i].label, this.newTreeData.nowNode, '123')
        if (tree[i].label == this.newTreeData.nowNode) {
          console.log(tree[i].children, '找到啦')
          if (!tree[i].children) {
            this.$set(tree[i], 'children', [])
          }
          tree[i].children.push({
            label: value.lbmc,
            type: String(Number(tree[i].type) + 1),
          })
          return
        } else {
          console.log('没找到')
          this.findTreeNode(tree[i].children, value)
        }
      }
    },
    // 类别信息取消按钮触发
    onCancelTree() {
      this.showNewTree = false
    },
    // 触发列配置弹框
    onShowColumn() {
      this.defaultColumnData = this.$options.data().columnData
      this.$refs.setColumnRef.dialogVisible = true
    },
    // 合计列计算
    getSummaries(param) {
      this.$nextTick(() => {
        this.$refs.tableList.doLayout()
      })
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.total + '条明细'
        } else if (this.arr.includes(column.property)) {
          const values = data.map((item) => delcommafy(item[column.property]))
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = delcommafy(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (this.monarr.includes(column.property)) {
              sums[index] = this.$formatMoney(sums[index])
            } else if (this.numarr.includes(column.property)) {
              sums[index] = this.$formatNumber(sums[index])
            }
          } else {
            sums[index] = ''
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 获取每页几条数据
    handleSizeChange(val) {
      this.pagesize = val
      this.getTableData()
    },
    // 获取当前第几页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },
    // 单据状态修改
    orderStatusChange(val) {
      // if (val == 5 || val == 0) {
      //   this.queryData.isShowHcdj = true
      // } else {
      //   this.queryData.isShowHcdj = false
      // }
    },
    // 搜索
    handleFilterMethod(value, label) {
      if (label == 'companyName') {
        this.gysOptions = this.filterMethod(this.gysOptions, value, label)
      } else if (label == 'storehouseName') {
        this.storehouseOptions = this.filterMethod(this.storehouseOptions, value, label)
      } else if (label == 'realname') {
        this.ywyOptions = this.filterMethod(this.ywyOptions, value, label)
      } else if (label == 'goodsName') {
        this.spmcOptions = this.filterMethod(this.spmcOptions, value, label)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: calc(100vh - 1.875117rem);
  background: #f0f2f5;
  box-sizing: border-box;
  padding: 0 8px 8px;
  display: flex;
  flex-direction: column;
}

.info_operation_btn {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;

  ::v-deep .el-button {
    width: 80px;
    height: 30px;
    text-align: center;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    border-radius: 5px;
    border: none;
    margin-right: 6px;
    margin-left: 0;
  }

  .el-button--default {
    color: #666;
  }

  ::v-deep .el-select {
    width: 120px;
    height: 30px;
    box-sizing: border-box;
    margin-right: 6px;

    .el-input {
      .el-input__inner {
        height: 30px;
        border: none;
        font-size: 12px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }

  .btn_left {
    width: 60%;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    p {
      font-size: 12px;
      color: #666;
      margin: 0 5px 0 10px;
    }

    ::v-deep .el-checkbox {
      display: flex;
      align-items: center;
      margin-left: 8px;
      margin-right: 8px;

      .el-checkbox__input {
        height: 15px;
      }

      .el-checkbox__label {
        font-size: 12px;
        padding-left: 5px;
        color: #666;
      }

      .is-checked {
        .el-checkbox__inner {
          background: #1a93fa;
          border-color: #1a93fa;
        }
      }
    }
  }

  .btn_right {
    width: 40%;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .el-input {
      width: 250px;
      height: 30px;
      margin-right: 6px;

      ::v-deep .el-input__inner {
        height: 30px;
        border: none;
        box-sizing: border-box;
        padding: 0 0.15rem;
        background: #fff;
        font-size: 12px;
        color: #666;

        &::placeholder {
          font-size: 12px;
          color: #c1c1c1;
        }
      }
    }

    .el-button {
      width: 60px;
    }

    .set_up {
      font-size: 23px;
      color: rgb(153, 153, 153);
    }
  }
}

.disabled_button {
  background: #cbced3 !important;
  color: #666 !important;
}

.info_content_div {
  width: 100%;
  height: calc(100% - 50px);
  background: #fff;
  box-sizing: border-box;
  padding: 0 12px;
  display: flex;

  .div_table {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .div_screen {
      width: 100%;
      // height: 100px;
      display: flex;
      justify-content: space-between;

      ::v-deep .el-select {
        width: 120px;
        height: 30px;
        box-sizing: border-box;
        border-radius: 4px;

        .el-input {
          .el-input__inner {
            height: 30px;
            border-color: #e3e3e3;
            font-size: 12px;
            padding-left: 6px;
          }

          .el-input__suffix {
            height: 30px;
            display: flex;
            align-items: center;
          }
        }
      }

      input {
        width: 120px;
        height: 30px;
        background: #ffffff;
        border: 1px solid #e3e3e3;
        opacity: 1;
        border-radius: 4px;
        font-size: 12px;
        color: #666;
        box-sizing: border-box;
        padding: 0 6px;

        &:focus {
          outline: none;
          border-color: #1890ff;
        }
      }

      ::v-deep .el-input {
        width: 120px;

        .el-input__inner {
          height: 30px;
          border-color: #e3e3e3;
          font-size: 12px;
          padding-left: 5px;
        }

        .el-input__suffix {
          height: 30px;
          display: flex;
          align-items: center;
        }
      }

      .screen_left {
        width: 14rem;
        height: 100%;
        box-sizing: border-box;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;

        > div {
          width: 180px;
          height: 30px;
          margin-top: 15px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          margin-right: 15px;

          > p {
            margin: 0;
            width: 50px;
            margin-right: 10px;
            font-size: 12px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #666666;
            text-align: justify;
            text-justify: distribute-all-lines;
            /*ie6-8*/
            text-align-last: justify;
            /* ie9*/
            -moz-text-align-last: justify;
            /*ff*/
            -webkit-text-align-last: justify;
            /*chrome 20+*/
          }
        }

        .line_dialog {
          .dialog_input {
            flex: 1;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            margin-right: 0;
            text-align: left;
            text-align-last: left;

            ::v-deep .el-select {
              i {
                display: none;
              }
            }

            i {
              position: absolute;
              right: 6px;
              color: #bfbfbf;
              font-size: 15px;
              cursor: pointer;
            }
          }
        }
      }
      .custom_item {
        display: flex;
        align-items: center;
        margin: 10px 10px 10px 0;
        width: 180px;
        font-size: 12px;
        .item_title {
          padding: 0 5px;
          width: auto;
          min-width: 60px;
          line-height: 30px;
          color: #666666;
          text-justify: distribute-all-lines;
          /*ie6-8*/
          text-align-last: justify;
          /* ie9*/
          -moz-text-align-last: justify;
          /*ff*/
          -webkit-text-align-last: justify;
          /*chrome 20+*/
        }
        .custom_select_head {
          flex: 1;
          height: 30px;
          position: relative;
          display: flex;
          align-items: center;

          ::v-deep .el-select {
            .el-input {
              .el-input__inner {
                height: 30px;
                border-color: #e3e3e3;
                font-size: 12px;
                padding-left: 8px;
              }

              .el-input__suffix {
                height: 30px;
                display: flex;
                align-items: center;
              }
            }
          }

          ::v-deep .el-checkbox {
            display: flex;
            align-items: center;
            margin-right: 0.25rem;

            .el-checkbox__input {
              height: 30px;
              display: flex;
              align-items: center;
            }

            .el-checkbox__label {
              font-size: 12px;
              padding-left: 10px;
              color: #666;
            }

            .is-checked {
              .el-checkbox__inner {
                background: #1a93fa;
                border-color: #1a93fa;
              }
            }
          }

          ::v-deep .el-input {
            width: 100%;

            .el-input__inner {
              height: 30px;
              border-color: #e3e3e3;
              font-size: 12px;
              padding-left: 5px;
            }

            .el-input__suffix {
              height: 30px;
              display: flex;
              align-items: center;
            }
          }

          ::v-deep .el-date-editor {
            width: 3.375211rem;
            height: 30px;
            background: #ffffff;
            border: 1px solid #d9d9d9;
            margin-right: 0.112507rem;
            padding: 3px 6px;

            .el-range__icon {
              position: absolute;
              right: 0;
              line-height: 30px;
            }

            .el-range-separator {
              line-height: 24px;
            }

            .el-range-input {
              font-size: 12px;
            }

            .el-range__close-icon {
              display: none;
            }
          }
        }
      }
      .screen_right {
        // (50+5+120+15)*4=760px
        width: calc(100% - 14rem);
        height: 100%;
        box-sizing: border-box;
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        box-sizing: border-box;
        padding-top: 15px;

        ::v-deep .el-button {
          width: 60px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          border-radius: 5px;
          border: none;
        }

        ::v-deep .el-select {
          width: 80px;
          margin-right: 6px;
        }

        ::v-deep .el-input {
          width: 80px;

          .el-input__inner {
            height: 30px;
            border-color: #e3e3e3;
            font-size: 12px;
            padding-left: 5px;
          }

          .el-input__suffix {
            height: 30px;
            display: flex;
            align-items: center;
          }
        }

        // .date_picker_style {
        //   width: 3.375211rem;
        //   height: 30px;
        //   background: #ffffff;
        //   border: 1px solid #d9d9d9;
        //   opacity: 1;
        //   border-radius: 0.075005rem;
        //   position: relative;
        //   display: flex;
        //   align-items: center;
        //   justify-content: space-between;
        //   box-sizing: border-box;
        //   padding: 5px;
        //   margin-right: 6px;
        //   position: relative;
        //   p {
        //     width: 100%;
        //     height: 30px;
        //     margin: 0;
        //     font-size: 0.018751rem;
        //     color: #666;
        //     font-family: HelveticaNeue;
        //     color: #666666;
        //     line-height: 30px;
        //   }
        //   i {
        //     font-size: 0.262514rem;
        //     color: #d9d9d9;
        //   }
        //   ::v-deep .el-date-editor {
        //     width: 3.375211rem;
        //     height: 30px;
        //     opacity: 0;
        //     position: absolute;
        //     top: 0;
        //     left: 0;
        //     z-index: 2001;
        //     .el-range-input {
        //       font-size: 12px;
        //     }
        //     .el-range-separator {
        //       line-height: 30px;
        //       font-size: 12px;
        //     }
        //   }
        // }
        ::v-deep .el-date-editor {
          width: 178px;
          height: 30px;
          background: #ffffff;
          border: 1px solid #d9d9d9;
          margin-right: 6px;
          padding: 3px 6px;

          .el-range__icon {
            position: absolute;
            right: 0;
            line-height: 30px;
          }

          .el-range-separator {
            line-height: 24px;
          }

          .el-range-input {
            font-size: 12px;
          }

          .el-range__close-icon {
            display: none;
          }
        }
      }
    }

    .table_content {
      // height: calc(100% - 150px - 15px);
      margin-top: 15px;

      ::v-deep .el-table {
        border: 1px solid #e3e3e3;
        border-bottom: none;
        box-sizing: border-box;

        th,
        td {
          padding: 0;
          color: #666;
          box-sizing: border-box;
          border-right: 1px solid #e3e3e3;

          .cell {
            min-height: 30px;
            display: flex;
            align-items: center;
            font-size: 12px;
            width: 100%;
          }

          &:first-child {
            .cell {
              justify-content: center;
              padding: 0;
            }
          }
        }

        th {
          .cell {
            background: #ededed;
            justify-content: center;
          }
        }

        .el-table__body tr:hover > td {
          background: #e3f6ff;
        }

        .el-table__footer-wrapper {
          td {
            background: #f4f4f4;
            border: none;
          }
        }

        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }

        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }

    .table_pagination {
      width: 100%;
      height: 50px;
      box-sizing: border-box;
      padding: 8px 0;
      display: flex;

      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;

          .el-pagination__sizes {
            margin: 0;

            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>